"""An example of embedding a RichJupyterWidget in a PyQT Application.
This uses a normal kernel launched as a subprocess. It shows how to shutdown
the kernel cleanly when the application quits.
To run:
    python3 embed_qtconsole.py
非阻塞的qtconsole,spyder用的就是这个。
添加了变量表格，以及变量传输。

"""
import sys
from PyQt5.Qt import QApplication
from PyQt5.QtWidgets import QMainWindow, QWidget, QHBoxLayout, QPushButton, QTableWidget, QTableWidgetItem
import importlib
from PyQt5 import sip

# import sip
import ast
import base64
import pickle

# The ID of an installed kernel, e.g. 'bash' or 'ir'.
USE_KERNEL = 'python3'
import plugin_manager.app_interface


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        plugin_manager.app_interface._MainWindow = self
        centralWidget = QWidget()
        layout = QHBoxLayout()
        centralWidget.setLayout(layout)
        b = QPushButton('重新加载插件')

        layout.addWidget(b)
        self.central_layout = layout
        self.ipythonWidget = centralWidget
        self.setCentralWidget(centralWidget)

        self.plugin_manager = PluginManager(self)
        b.clicked.connect(self.plugin_manager.reload_plugin)

        sys.path.append('/home/hzy/Documents/Development/python/pyqtdemos_for_opensource/plugins')
        self.module = importlib.import_module('demo_plugin.main')
        self.module.load()

    def add_widget(self, widget: QWidget):
        self.central_layout.addWidget(widget)


class PluginManager(object):
    def __init__(self, main_window: MainWindow):
        self.main_window = main_window
        self.plugins = {}

    def add_plugin(self):
        pass

    def load_plugin(self, plugin_widget: QWidget):
        self.main_window.add_widget(plugin_widget)
        self.plugins['a'] = plugin_widget

    def reload_plugin(self):
        widget = self.plugins['a']

        self.main_window.central_layout.removeWidget(widget)
        sip.delete(widget)
        self.main_window.module = importlib.reload(self.main_window.module)
        self.main_window.module.reload()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()

    # print(module)
    # import plugin_manager.plugin_for_test

    sys.exit(app.exec_())
